package com.snail.ron.design.singleton;

import java.io.*;

/**
 * @author xueguoping
 * @desc: TODO 序列化破坏
 * 创建对象的四种方式
 * new 通过构造方法 构造方法私有化就不存在被破坏
 * clone 必须实现Cloneable接口,单例模式是不可能实现这个接口的，排除
 * 反序列化
 * 反射
 * @date 2022/4/1209:17
 */
public class SingletonDestroyBySerializable {

    public static void main(String[] args)throws IOException,ClassNotFoundException{
        destroySingletonOne();
    }

    //序列化破坏SingletonOne
    private static void destroySingletonOne()throws IOException,ClassNotFoundException {
        SingletonOne singletonOne = null;
        SingletonOne singletonOneNew = null;

        singletonOne = SingletonOne.getInstance();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(singletonOne);

        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        singletonOneNew = (SingletonOne) ois.readObject();

        System.out.println(singletonOne == singletonOneNew);
    }
}
